import { Example } from '~/server/models/example.model';
import { objectIdSchema, updateExampleSchema } from '~/server/schemas/example.schema';
import { validateBody, validateParam } from '~/server/utils/validation.server';

export default defineEventHandler(async (event) => {
  // 校验路由参数 ID
  const id = validateParam(event, objectIdSchema, 'id');

  // 校验请求体数据
  const validatedData = await validateBody(event, updateExampleSchema);

  // 检查是否有数据需要更新
  if (Object.keys(validatedData).length === 0) {
    throw createError({
      statusCode: 400,
      statusMessage: '至少需要提供一个字段进行更新',
    });
  }

  // 查找并更新数据
  const updatedExample = await Example.findByIdAndUpdate(
    id,
    { ...validatedData, updatedAt: new Date() },
    { new: true, runValidators: true },
  );

  if (!updatedExample) {
    throw createError({
      statusCode: 404,
      statusMessage: '未找到指定的数据',
    });
  }

  return updatedExample;
});
